
from socketserver import StreamRequestHandler, TCPServer
import socket

class EchoHandler(StreamRequestHandler):
    '''
    将一个类文件接口放置在底层socket上
    需要注意下：发送消息时，需要加上换行符，不然客户端会挂起
    '''

    # Optional settings (defaults shown)
    timeout = 5                      # Timeout on all socket operations
    rbufsize = -1                    # Read buffer size
    wbufsize = 0                     # Write buffer size
    disable_nagle_algorithm = False  # Sets TCP_NODELAY socket option    
    def handle(self):
        print('Got connection from', self.client_address)
        try:
            # self.rfile is a file-like object for reading
            for line in self.rfile:
                # self.wfile is a file-like object for writing
                self.wfile.write(line)
        except socket.timeout:
            print('Timed out!')
if __name__ == '__main__':
    '''创建一个TCP服务器'''
    serv = TCPServer(('', 20001), EchoHandler)
    serv.serve_forever()
